package 服务端和客户端互发消息;

import java.time.LocalDateTime;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class MyClientHandler extends SimpleChannelInboundHandler<String> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		// 只用对方调用ChannelHandlerContext中writeAndFlush方法就会抵用我方channelRead0方法。
		System.out.println(ctx.channel().remoteAddress());
		System.out.println("client output: " + msg);
		ctx.writeAndFlush("from client: " + LocalDateTime.now());//此方法会调用服务端的channelRead0的方法。
		Thread.sleep(2000);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// 当通道建立好时会被调用，只调用一次。
		ctx.writeAndFlush("来自客户端的问候！");
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// TODO Auto-generated method stub
		cause.printStackTrace();
		ctx.close();
	}
}
